/*********************************************************************************
 *FileName:  adc.c
 *Author:    ChenJiehong
 *Version:   V1.0
 *Date:      2023-10-15
 ****************************************Includes***********************************/
#include "adc.h"

/***************************************Variables***********************************/
Adc_Result_t Adc_Result;

/***************************************Functions***********************************/
void adc_init(void)
{
    ADC_InitTypeDef ADC_InitStruct;
    SYSCTRL_Unlock();
    RCC_SystemClockControl(RCC_APBPeriph_Clock, ENABLE);
    RCC_AHBPeriphClockCmd(RCC_AHBPeriph_ADC, ENABLE);
    NVIC_EnableIRQ(ADC_IRQn);

    ADC_InitStruct.ADC_ClockSource = ADC_ClockSource_32M;
    ADC_InitStruct.ADC_TrigSource = ADC_TrigSource_EPWM0;
    ADC_InitStruct.ADC_OnDelayTimeCyecles = 0;
    ADC_InitStruct.ADC_StableTimeCyecles = 10;
    ADC_InitStruct.ADC_ConvTimeCyecles = 20;
    ADC_InitStruct.ADC_SampleTimeCyecles = 20;
    ADC_InitStruct.ADC_ConvMode = ADC_ConvMode_Single;
    ADC_InitStruct.ADC_RefVoltageSource = ADC_VRef_Internal;

    ADC_Init(ADC, &ADC_InitStruct);

    ADC_QueueConfig(ADC, ADC_Queue_Rank1, ADC_Channel_MVSS0, ADC_PGA_Gain_1, ADC_Rank_Enable);
    ADC_QueueConfig(ADC, ADC_Queue_Rank2, ADC_Channel_BVDD, ADC_PGA_Gain_1, ADC_Rank_Enable);
	ADC_QueueConfig(ADC, ADC_Queue_Rank3, ADC_Channel_TEMP, ADC_PGA_Gain_1, ADC_Rank_Enable);
    ADC_ITConfig(ADC, ADC_IT_EOC, ENABLE);

    ADC_Cmd(ADC, ENABLE);
}

int16_t getTemperature(uint16_t u16ADC_Value)
{
    /* T = (TST - DTV)*(TSA/4096) */
    /* DTV = u16ADC_Value */
    /* TST = 0x556 */
    /* TSA = 0X3DA */
    return (int16_t)(0x556 - u16ADC_Value) * 0x3DA / 4096;
}

uint16_t getVoltage_Unfiltered(uint16_t u16ADC_Value)
{
    /* return  uint16_t the voltage in 10 mV */
    return ((uint32_t)u16ADC_Value * 40000 / 4095);
}


int16_t getCurrent_Unfiltered(int16_t i16ADC_Value)
{
		/* ADC_Code/4095*2000 = Voltage, Voltage/R_SHUNT = Current * Gain Gain = 10*/
		/* ADC_Code/4095*2000 *1000/100 */
    return (int16_t)((int32_t)i16ADC_Value*20000/4095);
}

uint16_t adc_ConvertToCurrent(int16_t i16ADC_Value)
{
		uint16_t u16Current = 0;
		int16_t i16Current = getCurrent_Unfiltered(i16ADC_Value);
	
		if(i16Current>0)
		{
			u16Current = i16Current;
		}
		else
		{
			u16Current = 0;
		}

		return u16Current;
}

void ADC_IRQHandler(void)
{
    if (ADC_GetITStatus(ADC, ADC_IT_EOC))
    {
        // 中断 为了提高效率  直接赋值，不调用库函数
        Adc_Result.MotorCurrent = ADC->DR1;
        Adc_Result.SupplyVoltage = ADC->DR2;
        Adc_Result.Temperature = ADC->DR3;
        ADC_ClearITPendingBit(ADC, ADC_IT_EOC);
    }
}

/***************************************END OF FILE*********************************/
